{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python3 网络编程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "\n",
    "\n",
    "Python 提供了两个级别访问的网络服务。：\n",
    "\n",
    "低级别的网络服务支持基本的 Socket，它提供了标准的 BSD Sockets API，可以访问底层操作系统Socket接口的全部方法。\n",
    "高级别的网络服务模块 SocketServer， 它提供了服务器中心类，可以简化网络服务器的开发。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "socket()函数\n",
    "Python 中，我们用 socket（）函数来创建套接字，语法格式如下：\n",
    "\n",
    "socket.socket([family[, type[, proto]]])\n",
    "参数\n",
    "family: 套接字家族可以使AF_UNIX或者AF_INET\n",
    "type: 套接字类型可以根据是面向连接的还是非连接分为SOCK_STREAM或SOCK_DGRAM\n",
    "protocol: 一般不填默认为0.\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "'''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "连接地址: ('10.32.3.200', 55247)\n"
     ]
    }
   ],
   "source": [
    "#  服务端\n",
    "\n",
    "import socket\n",
    "import sys\n",
    "\n",
    "# 创建 socket 对象\n",
    "serversocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n",
    "\n",
    "# 获取本地主机名\n",
    "host = socket.gethostname()\n",
    "\n",
    "port = 9999\n",
    "\n",
    "# 绑定端口号\n",
    "serversocket.bind((host,port))\n",
    "\n",
    "# 设置最大连接数，超过后排队\n",
    "connectSize = 5\n",
    "serversocket.listen(connectSize)\n",
    "\n",
    "while True:\n",
    "         # 建立客户端连接\n",
    "        clientsocket,addr = serversocket.accept()\n",
    "        print('连接地址: %s'% str(addr))\n",
    "        msg = '成功连接到服务器'\n",
    "        clientsocket.send(msg.encode('utf-8'))\n",
    "        clientsocket.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
